package com.ruoyi.info.utils;

import com.ruoyi.info.domain.FhInfoPointsHistory;
import com.ruoyi.info.domain.FhInfoUser;
import com.ruoyi.info.service.IFhInfoPointsHistoryService;
import com.ruoyi.info.service.IFhInfoUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 积分工具类
 * 统一处理积分增减和记录
 * 
 * @author ruoyi
 */
@Component
public class PointsUtil {

    @Autowired
    private IFhInfoUserService fhInfoUserService;

    @Autowired
    private IFhInfoPointsHistoryService fhInfoPointsHistoryService;

    /**
     * 增加积分
     * 
     * @param userId 用户ID
     * @param points 增加的积分
     * @param sourceType 来源类型（task_complete=完成任务，signin=签到，comment=评论，like=点赞，add_friend=添加好友，post_content=发布动态）
     * @param sourceId 来源ID（如任务ID等）
     * @param remark 备注说明
     * @return 是否成功
     */
    @Transactional
    public boolean addPoints(Long userId, Long points, String sourceType, Long sourceId, String remark) {
        try {
            // 获取用户信息
            FhInfoUser user = fhInfoUserService.selectFhInfoUserByUserId(userId);
            if (user == null) {
                return false;
            }

            // 获取当前积分
            Long pointsBefore = user.getPoints() != null ? user.getPoints() : 0L;
            Long pointsAfter = pointsBefore + points;

            // 更新用户积分
            user.setPoints(pointsAfter);
            fhInfoUserService.updateFhInfoUser(user);

            // 记录积分流水
            FhInfoPointsHistory history = new FhInfoPointsHistory();
            history.setUserId(userId);
            history.setChangePoints(points);
            history.setPointsBefore(pointsBefore);
            history.setPointsAfter(pointsAfter);
            history.setOpType("1"); // 1=增加
            history.setSourceType(sourceType);
            history.setSourceId(sourceId);
            history.setRemark(remark);
            history.setCreateTime(LocalDateTime.now());
            fhInfoPointsHistoryService.insertFhInfoPointsHistory(history);

            return true;
        } catch (Exception e) {
            throw new RuntimeException("增加积分失败: " + e.getMessage(), e);
        }
    }

    /**
     * 减少积分
     * 
     * @param userId 用户ID
     * @param points 减少的积分
     * @param sourceType 来源类型（exchange=兑换等）
     * @param sourceId 来源ID（如订单ID等）
     * @param remark 备注说明
     * @return 是否成功
     */
    @Transactional
    public boolean subtractPoints(Long userId, Long points, String sourceType, Long sourceId, String remark) {
        try {
            // 获取用户信息
            FhInfoUser user = fhInfoUserService.selectFhInfoUserByUserId(userId);
            if (user == null) {
                return false;
            }

            // 获取当前积分
            Long pointsBefore = user.getPoints() != null ? user.getPoints() : 0L;
            
            // 检查积分是否足够
            if (pointsBefore < points) {
                throw new RuntimeException("积分不足");
            }

            Long pointsAfter = pointsBefore - points;

            // 更新用户积分
            user.setPoints(pointsAfter);
            fhInfoUserService.updateFhInfoUser(user);

            // 记录积分流水
            FhInfoPointsHistory history = new FhInfoPointsHistory();
            history.setUserId(userId);
            history.setChangePoints(-points); // 负数表示减少
            history.setPointsBefore(pointsBefore);
            history.setPointsAfter(pointsAfter);
            history.setOpType("2"); // 2=减少
            history.setSourceType(sourceType);
            history.setSourceId(sourceId);
            history.setRemark(remark);
            history.setCreateTime(LocalDateTime.now());
            fhInfoPointsHistoryService.insertFhInfoPointsHistory(history);

            return true;
        } catch (Exception e) {
            throw new RuntimeException("减少积分失败: " + e.getMessage(), e);
        }
    }
}

